package br.ufal.tci.nexos.arcolive.service.connection.command;

import br.ufal.tci.nexos.arcolive.command.ArCoLIVEClientCommand;
import br.ufal.tci.nexos.arcolive.command.ArCoLIVECommandResult;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVEPersistenceException;
import br.ufal.tci.nexos.arcolive.participant.ArCoLIVEParticipant;
import br.ufal.tci.nexos.arcolive.persistence.ArCoLIVEPersistence;
import br.ufal.tci.nexos.arcolive.persistence.ArCoLIVEPersistenceConnectionPoll;
import br.ufal.tci.nexos.arcolive.persistence.GenericResultSet;
import br.ufal.tci.nexos.arcolive.service.connection.ConnectionRequest;

public class LoginCommand extends ArCoLIVEClientCommand {
	
	public LoginCommand(ConnectionRequest request) {
		super(request);
	}
	
	public ArCoLIVECommandResult executeImpl() {
		ArCoLIVEPersistenceConnectionPoll pcp;
		ArCoLIVEPersistence persistence;
		ArCoLIVEParticipant participant = (ArCoLIVEParticipant) this.request.getOwner();
		String response;
		
		try {
			pcp = ArCoLIVEPersistenceConnectionPoll.getInstance();
			persistence = pcp.getDatabaseConnection();
		} catch (ArCoLIVEPersistenceException e) {
			response = "0";
			return new ArCoLIVECommandResult(this, response, e);
		}
		
		String username = this.request.getStringParameter("username");
		String password = this.request.getStringParameter("password");
		
		if (persistence.authenticateUser(username, password)) {
			GenericResultSet participantData = persistence.getOneParticipant(username);
			participant.getParticipantDescriptor().setParticipantId(participantData.getIntValue("participantId"));
			response = "1";
		} else {
			response = "0";
			return new ArCoLIVECommandResult(this, response, new Exception("Username or Password incorrect"));
		}
			
		return new ArCoLIVECommandResult(this, response);
	}

}